import { ws } from '../config/config'


abstract class WsEvent implements IWsEvent {
  #connecting = false//正在连接
  _readyState = null
  abstract  init(url: string | URL, protocols?: string | string[]):void;
  onclose(this: WebSocket, ev: CloseEvent):any {
      
  }
  onerror: (this: WebSocket, ev: Event) => {
    
  }
  onmessage: (this: WebSocket, ev: MessageEvent<any>) => {
    
  }
  onopen: (this: WebSocket, ev: Event) => {
    
  }
  close(code?: number, reason?: string): void {
    throw new Error('Method not implemented.')
  }
  send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {
    throw new Error('Method not implemented.')
  }
  
}

interface IWsEvent { 
  onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;
  onerror: ((this: WebSocket, ev: Event) => any) | null;
  onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;
  onopen: ((this: WebSocket, ev: Event) => any) | null;
  /**
   * Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
   */
  close(code?: number, reason?: string): void;
  /**
   * Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
   */
  send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
}



class WS extends WsEvent{
  
  #readyStateStr:Array<string>=['正在连接', '连接成功', '正在关闭', '连接关闭']
  #ws = null
  #wsUrl = null
  
  init(url: string | URL, protocols?: string | string[]): void{
    if (window.WebSocket == undefined) {
      throw new Error("WebSocket is not supported by your browser!");
    }
    this.#wsUrl = url;
    this.#ws = new WebSocket(url, protocols);
  }
  get wsStatus() {
    this._readyState=this.#ws.readyState
    if (this._readyState == null) { 
      this._readyState = 3;
    }
    return this.#readyStateStr[this._readyState]
  }
  get ws() { 
    return this.#ws
  }
  send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void {
    throw new Error('Method not implemented.')
  }
}
